package com.yf.mediaserver.gb.sip.processors.req.impl;

import com.yf.mediaserver.gb.sip.processors.SIPProcessorObserver;
import com.yf.mediaserver.gb.sip.processors.SIPSender;
import com.yf.mediaserver.gb.sip.processors.req.ISIPRequestProcessor;
import com.yf.mediaserver.gb.sip.processors.req.SIPRequestProcessorParent;
import com.yf.mediaserver.gb.sip.util.RemoteAddressInfo;
import com.yf.mediaserver.gb.sip.util.SipUtils;
import gov.nist.javax.sip.address.AddressImpl;
import gov.nist.javax.sip.address.SipUri;
import gov.nist.javax.sip.message.SIPRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sip.RequestEvent;
import javax.sip.SipFactory;
import javax.sip.header.FromHeader;
import javax.sip.header.ViaHeader;
import javax.sip.message.Response;

/**
 * SIP命令类型： MESSAGE 请求
 */
@Slf4j
@Component
public class MessageRequestProcessor extends SIPRequestProcessorParent implements InitializingBean, ISIPRequestProcessor {

    public final static String method = "MESSAGE";

    @Resource
    private SIPSender sipSender;

    @Resource
    private SIPProcessorObserver processorObserver;

    @Override
    public void afterPropertiesSet()  {
        processorObserver.addRequestProcessor(method,this);
    }

    @Override
    public void process(RequestEvent evt) {
        try {
            SIPRequest request = (SIPRequest) evt.getRequest();
            // 注册标志
            FromHeader fromHeader = (FromHeader) request.getHeader(FromHeader.NAME);
            AddressImpl address = (AddressImpl) fromHeader.getAddress();
            SipUri uri = (SipUri) address.getURI();
            String deviceId = uri.getUser();
            log.info("当前请求设备ID:{}", deviceId);

            RemoteAddressInfo remoteAddressInfo = SipUtils.getRemoteAddressFromRequest(request, false);
            String requestAddress = remoteAddressInfo.getIp() + ":" + remoteAddressInfo.getPort();
            log.info("[MESSAGE请求] 设备：{}, 开始处理: {}", deviceId, requestAddress);
            // 判断TCP还是UDP
            ViaHeader reqViaHeader = (ViaHeader) request.getHeader(ViaHeader.NAME);
            String transport = reqViaHeader.getTransport();
            log.info("注册方式：{}", transport);


            String hostAddress = request.getLocalAddress().getHostAddress();
            Response response = SipFactory.getInstance().createMessageFactory().createResponse(Response.OK, request);
            sipSender.simpleSend(hostAddress, response);

        } catch (Exception e) {
            log.error("未处理的异常 ", e);
        }
    }


}
